package com.kyxx.topics.fragment;

import android.app.ActivityOptions;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kyxx.topics.BaseApp;
import com.kyxx.topics.MainActivity;
import com.kyxx.topics.R;
import com.kyxx.topics.activity.AddYouHuiQuanActivity;
import com.kyxx.topics.activity.DetailYouHuiQuanActivity;
import com.kyxx.topics.bean.CouponBean;
import com.kyxx.topics.net.LoadingStringCallBack;
import com.kyxx.topics.net.OkGoRequest;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.Constants;
import com.kyxx.topics.view.CircleImageView;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.request.BaseRequest;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;
import yyydjk.com.library.CouponView;

public class YouHuiQuanFragment extends Fragment {
    private LinearLayout ll_no;
    private ImageView iv_add_quan;
    private ListView lv_youhuiquan;
    private SwipeRefreshLayout srl;
    private int lastVisiblePosition;
    private int pageSize = 1;
    private int countSize = 1000;
    private YouHuiQuanAdapter youHuiQuanAdapter;
    private List<CouponBean> couponBeanList = new ArrayList<>();
    private ImageLoader imageLoader = ImageLoader.getInstance();
    private DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
            .cacheOnDisk(true)
            .imageScaleType(ImageScaleType.EXACTLY)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .showImageOnFail(R.mipmap.image_default)
            .showImageOnLoading(R.mipmap.image_default)
            .showImageForEmptyUri(R.mipmap.image_default)
            .build();

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_you_hui_quan, container, false);
        iv_add_quan = (ImageView) view.findViewById(R.id.iv_add_quan);
        lv_youhuiquan = (ListView) view.findViewById(R.id.lv_youhuiquan);
        srl = (SwipeRefreshLayout) view.findViewById(R.id.srl);
        ll_no = (LinearLayout) view.findViewById(R.id.ll_no);
        srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initData();
            }
        });
        lv_youhuiquan.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                if (lastVisiblePosition == lv_youhuiquan.getLastVisiblePosition())
                    return;
                lastVisiblePosition = lv_youhuiquan.getLastVisiblePosition();
                Log.e("topic", lastVisiblePosition + "onScroll" + lv_youhuiquan.getCount());
                if (lastVisiblePosition == lv_youhuiquan.getCount() - 2 && lv_youhuiquan.getCount() >= countSize) {
                    pageSize++;
                }
            }
        });
        youHuiQuanAdapter = new YouHuiQuanAdapter();
        lv_youhuiquan.setAdapter(youHuiQuanAdapter);
        lv_youhuiquan.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(getActivity(), DetailYouHuiQuanActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", couponBeanList.get(i));
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        lv_youhuiquan.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int i, long l) {
                new AlertDialog.Builder(getActivity()).setItems(new String[]{"删除(刪除后无法恢复)"}, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which){
                            case 0:
                                deleteQuan(couponBeanList.get(i).getId());
                                break;
                        }
                    }
                }).setNegativeButton("取消", null).show();
                return true;
            }
        });
        initData();
        iv_add_quan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), AddYouHuiQuanActivity.class));
            }
        });
        return view;
    }

    class YouHuiQuanAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return couponBeanList.size();
        }

        @Override
        public Object getItem(int i) {
            return couponBeanList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            final ViewHolder holder;
            if (view == null) {
                holder = new ViewHolder();
                view = View.inflate(getActivity(), R.layout.item_youhuiquan, null);
                holder.civ_huiyuanka = (CircleImageView) view.findViewById(R.id.civ_huiyuanka);
                holder.tv_name = (TextView) view.findViewById(R.id.tv_name);
                holder.tv_count = (TextView) view.findViewById(R.id.tv_count);
                holder.tv_time = (TextView) view.findViewById(R.id.tv_time);
                holder.tv_other = (TextView) view.findViewById(R.id.tv_other);
                holder.cv_top = (CouponView) view.findViewById(R.id.cv_top);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            final CouponBean couponBean = couponBeanList.get(i);
            imageLoader.displayImage(UrlUtils.BASEHTTP + couponBean.getImage(), holder.civ_huiyuanka, options);
            holder.tv_name.setText(couponBean.getTitle());
            if (couponBean.getType() == 1) {//体验券
                holder.tv_count.setText("剩余" + couponBean.getTimes_leave() + "次  " + "共" + couponBean.getTimes_total() + "次");
            } else if (couponBean.getType() == 2) {//抵扣券
                holder.tv_count.setText("满" + couponBean.getJianmian() + "元  " + "抵扣" + couponBean.getDikou() + "元");
            }
//            String[] colors=new String[3];
//            try {
//                colors = couponBean.getColor().split(",");
//            } catch (Exception e) {
//                e.printStackTrace();
//                colors[0] = "242";
//                colors[1] = "178";
//                colors[2] = "28";
//            }
            GradientDrawable drawable = (GradientDrawable) holder.cv_top.getBackground();
            if (couponBean.getColor() == null || couponBean.getColor().contains(",")) {
                couponBean.setColor("FF2e2e2e");
            } else {
                couponBean.setColor("FF" + couponBean.getColor());
            }
            int b = new java.math.BigInteger(couponBean.getColor(), 16).intValue();
            drawable.setColor(b);
            holder.tv_time.setText(couponBean.getDeadtime());
            holder.tv_other.setText(couponBean.getShop_name());
//            view.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    Intent intent = new Intent(getActivity(), DetailYouHuiQuanActivity.class);
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable("bean", couponBean);
//                    intent.putExtras(bundle);
//                    if (android.os.Build.VERSION.SDK_INT > 20) {
//                        startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(getActivity(), holder.civ_huiyuanka, "transitionImg").toBundle());
//                    } else {
//                        startActivity(intent);
//                    }
//                }
//            });
            return view;
        }
    }

    class ViewHolder {
        private ImageView civ_huiyuanka;
        private TextView tv_name;
        private TextView tv_count;
        private TextView tv_time;
        private TextView tv_other;
        private CouponView cv_top;
    }

    public void initData() {
        HttpParams params = new HttpParams();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uid", BaseApp.getModel().getId());
        jsonObject.put("page", pageSize);
        params.put("json", jsonObject.toString());
        String cachekey = UrlUtils.GETCOUPONLIST + "&uid=" + BaseApp.getModel().getId() + "&page=" + pageSize;
        OkGoRequest.post(UrlUtils.GETCOUPONLIST, getActivity(), cachekey, CacheMode.REQUEST_FAILED_READ_CACHE, params, new StringCallback() {

            @Override
            public void onBefore(BaseRequest request) {
                super.onBefore(request);
                if (srl != null)
                    srl.setRefreshing(true);
            }

            @Override
            public void onAfter(@Nullable String s, @Nullable Exception e) {
                super.onAfter(s, e);
                if (srl != null)
                    srl.setRefreshing(false);
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    org.json.JSONObject result = new org.json.JSONObject(s);
                    couponBeanList = JSON.parseArray(result.getJSONArray("data").toString(), CouponBean.class);
                    if (couponBeanList.size() == 0) {
                        if (ll_no != null)
                            ll_no.setVisibility(View.VISIBLE);
                    } else {
                        if (ll_no != null)
                            ll_no.setVisibility(View.GONE);
                    }
                    youHuiQuanAdapter.notifyDataSetChanged();
//                    youHuiQuanAdapter = new YouHuiQuanAdapter();
//                    lv_youhuiquan.setAdapter(youHuiQuanAdapter);

                } catch (JSONException e) {
                    e.printStackTrace();
                    if (ll_no != null)
                        ll_no.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    public void deleteQuan(String quanId) {
        HttpParams params = new HttpParams();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uid", BaseApp.getModel().getId());
        jsonObject.put("coupon", quanId);
        params.put("json", jsonObject.toString());
        OkGoRequest.post(UrlUtils.delCoupon, getActivity(), "delQuan", CacheMode.NO_CACHE, params, new LoadingStringCallBack(getActivity(), true) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                initData();
            }
        });
    }
}
